<!-- 部门树 -->
<template>
  <el-card shadow="never">
    <el-tree
      ref="settingTreeRef"
      class="fix-item mt-2"
      :data="tree"
      node-key="id"
      :props="{ children: 'children', label: 'name', disabled: '' }"
      v-loading="loading"
      style="--fix-top-height: 42px; overflow-y: auto"
      :expand-on-click-node="false"
      :filter-node-method="handleFilter"
      default-expand-all
      highlight-current
      draggable
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span class="node-item">
            <el-button
              v-if="data.level >= '2'"
              type="primary"
              link
              size="small"
              @click="handleEdit(data)"
              ><i-ep-edit
            /></el-button>
            <el-button
              v-if="data.level >= 1"
              type="warning"
              link
              size="small"
              @click="handleAdd(data)"
              ><i-ep-plus
            /></el-button>
            <el-button
              v-if="data.level >= '2'"
              type="danger"
              link
              size="small"
              @click="handleDelete(node, data)"
              ><i-ep-delete
            /></el-button>
          </span>
        </span>
      </template>
    </el-tree>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      draggable
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="settingFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入名称"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="专家类型" prop="bridgeType">
          <dictionary v-model="formData.bridgeType" type-code="bridgeType" />
        </el-form-item>

        <el-form-item label="所属菜单" prop="category">
          <dictionary v-model="formData.category" type-code="category" />
        </el-form-item>

        <el-form-item label="值" prop="type">
          <el-input
            v-model="formData.type"
            maxlength="20"
            placeholder="请输入病害类型值(-1为全部)"
          />
        </el-form-item>

        <el-form-item label="问题描述" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="200"
            placeholder="请输入问题描述"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
            :max="999"
            step-strictly
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { listSetting } from "@/api/ai/setting/index";
import { SettingVO } from "@/api/ai/setting/types";
import { DiseaseTypeForm } from "@/api/ai/disease-type/types";
import {
  saveDiseaseType,
  deleteDiseaseType,
  getDiseaseTypeForm,
} from "@/api/ai/disease-type/index";

const props = defineProps({
  modelValue: {
    type: Object,
    default: undefined,
  },
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  width: 800,
  title: "新增病害类型",
});

const settingFormRef = ref(ElForm);
const settingTreeRef = ref(null);

const loading = ref(false);
// 树列表
const tree = ref<TreeResult<SettingVO>[]>([]);

const emits = defineEmits(["node-click"]);
// 表单数据
const formData = reactive<DiseaseTypeForm>({
  sort: 0,
});
// 校验规则
const rules = reactive({
  name: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  bridgeType: [
    { required: true, message: "桥梁类型不能为空", trigger: "blur" },
  ],
  category: [{ required: true, message: "所属菜单不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});

/** 筛选 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }

  return data.name.indexOf(value) !== -1;
}

/** 部门树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  const params = { ...data.data };
  // 这里需要设置查询参数，问题的type为空
  if (params.type) {
    params.diseaseType = params.type;
    params.type = "";
  }
  const childrenLen = data.children?.length || 0;
  // 叶子节点才能添加问题
  emits("node-click", params, childrenLen == 0);
}

// 默认选中第一个节点
function defaultCheck(data: TreeResult<SettingVO>[]) {
  const first = data.find((it) => {
    return it.data.bridgeType == props.modelValue.bridgeType;
  });
  if (!first) {
    return;
  }
  const checked = first.children.find((it) => {
    return it.data.category == props.modelValue.category;
  });
  if (!checked) {
    return;
  }

  // 要加nextTick才可以选中
  nextTick(() => {
    settingTreeRef.value.setCurrentKey(checked.id, true);
  });
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  formData.id = undefined;
  formData.pid = undefined;
}

// 弹窗
function handleAdd(it) {
  reset();

  const len = it.children?.length + 1 || 1;
  // 二级菜单添加三级菜单的pid=0
  if (it.level == 1) {
    formData.type = `${len}`;
    formData.pid = "0";
  } else {
    formData.type = `${it.data.type}-${len}`;
    formData.pid = it.data.id;
  }

  formData.bridgeType = it.data.bridgeType;
  formData.category = it.data.category;
  formData.sort = len;
  dialog.visible = true;
}

// 编辑
function handleEdit(it) {
  getDiseaseTypeForm(it.data.id).then(({ data }) => {
    Object.assign(formData, data);
    dialog.visible = true;
  });
}

// 删除
function handleDelete(node, data) {
  ElMessageBox.confirm("确认删除病害分类?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteDiseaseType([data.data.id]).then(() => {
      ElMessage.success("删除成功");
      listTree();
    });
  });
}

// 新增类型
function handleSubmit() {
  settingFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      saveDiseaseType(formData)
        .then(() => {
          if (id) {
            ElMessage.success("修改成功");
          } else {
            ElMessage.success("新增成功");
          }
          closeDialog();
          listTree();
        })
        .finally(() => (loading.value = false));
    }
  });
}
function reset() {
  formData.bridgeType = "";
  formData.category = "";
  formData.name = "";
  formData.remark = "";
  formData.sort = 1;
  formData.type = "";
}
function listTree() {
  loading.value = true;
  listSetting().then(({ data }) => {
    tree.value = data;
    loading.value = false;
    defaultCheck(data);
  });
}

onBeforeMount(() => {
  listTree();
});
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;

  .node-item {
    display: none;
  }

  &:hover {
    .node-item {
      display: block;
    }
  }
}
</style>
